<template>
	<view class="ss">
		<view class="content">
			<text>上传照片</text>
		<view class="sahngpintupian">
			<view class="pic" @click="chooseImage()" :style="backgroundStyle">
				
				<img :src="imgUrl" class="img"/>
			</view>
		</view>
		<view class="example">
						<!-- 基础表单校验 -->
						<uni-forms ref="valiForm" :rules="rules" :modelValue="xx">
							<uni-forms-item label="商品名称" label-width="80px" required name="goodsName">
								<uni-easyinput v-model="xx.goodsName" placeholder="请输入" @blur="validateTitle('goodsName')" />
							</uni-forms-item>
							<uni-forms-item label="商品品种"  label-width="80px" required name="varietys">
								<uni-easyinput v-model="xx.varietys" placeholder="请输入" @blur="validateTitle('varietys')"/>
							</uni-forms-item>
							
							<uni-forms-item label="商品单位"   label-width="80px"required name="goodsUnit">
								<uni-data-select
								        v-model="xx.goodsUnit"
								        :localdata="range"
								        @change="validateTitle('goodsUnit')"
								      ></uni-data-select>
							</uni-forms-item>
							<uni-forms-item label="商品分类" label-width="80px" required name="categoryId">
								<uni-data-select
								        v-model="xx.categoryId"
								        :localdata="pinrange"
								        @change="validateTitle('categoryId')"
								      ></uni-data-select>
							</uni-forms-item>
							<uni-forms-item label="商品简介" label-width="80px" required name="introduces">
								<uni-easyinput v-model="xx.introduces" placeholder="请输入" @blur="validateTitle('introduces')"/>
							</uni-forms-item>
							<uni-forms-item label="商品价格"  label-width="80px" required name="gjprices">
								<uni-easyinput v-model="xx.gjprices" placeholder="请输入" @blur="validateTitle('gjprices')"/>
							</uni-forms-item>
						</uni-forms>
						
					</view>
		<view>
			<button type="primary" @click="submit('valiForm')">提交</button>
		</view>	
		</view>
		
	</view>
</template>

<script setup>
import { ref } from 'vue';
import {http} from '/until/request.js'
import {onLoad} from '@dcloudio/uni-app'
const backgroundImageUrl=ref('../../static/img-scspt@3x.png')
const tijiao=ref(false)
const imgUrl=ref(null)
const imgFile=ref('')
const xx=ref({goodsName:'',
		goodsPice:'',
		goodsUnit:'',
		categoryId:'',
		gjprices:'',
		varietys:'',
		introduces:''})
const value=ref('')

const range=ref([
		{value:1,text:'件'},
		{value:2,text:'公斤'}
	])
	const pinzhong=ref('')
	const pinrange=ref([])
	const validationErrors=ref(null)
	const isValid = ref(true);
	//校验
const validateTitle=(rex)=>{
	const vv = xx.value[rex];
	console.log(vv)
	const shuzi = /^\d+(\.\d+)?$/;
  if(vv !== undefined && vv !== null &&vv!==''){
	 switch (rex) {
    case 'goodsName':
      isValid.value = vv.trim() !== '';
      break;
    case 'goodsUnit':
      isValid.value = vv !== '';
      break;
    case 'categoryId':
      isValid.value = vv !== '';
      break;
    case 'gjprices':
      isValid.value = shuzi.test(vv);
      break;
    default:
      isValid.value = true;
  } 
  }else{
	  isValid.value = false;
  }
  if (!isValid.value) {
      const chineseLabels = {
        goodsName: '商品名称',
        goodsUnit: '商品单位',
        categoryId: '商品分类',
        gjprices: '价格',
		varietys:'商品品种',
		introduces:'商品简介',
		goodsPice:'商品照片'
      };
      const label = chineseLabels[rex] || rex;
     if (rex === 'gjprices') {
		  validationErrors[rex] = `${label} 必须是一个有效的数字`;
         
         } else {
			  validationErrors[rex] = `${label} 不能为空`;
           
         }
      uni.showToast({
        title:validationErrors[rex],
        icon: 'none',
        duration: 2000
      });
    } else {
      delete validationErrors[rex];
    }}
	 
	//商品分类
	const oo=ref([])
	const shangpinff=async()=>{
		let ll=await http({
			url:'/lft/stypes/strpe'
		})
		console.log(ll.data)
		oo.value=ll.data
		console.log(oo.value)
		for(let i=0;oo.value.length;i++){
			const qq=oo.value[i]
			const cc={value:qq.num,text:qq.tname}
			pinrange.value.push(cc)
		}
		console.log(pinrange.value)
	}
	//上传图片
	const chooseImage=()=>{
		uni.chooseImage({
		  count: 1, // 默认9, 一次可以选择的图片数量
		  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
		  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		  success: function(res) {
		    console.log('选择图片成功:', res); // 打印整个 res 对象
		
		    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
		      console.log('图片路径:', res.tempFilePaths[0]); // 打印图片路径
		      imgUrl.value = res.tempFilePaths[0];
		      imgFile.value = res.tempFiles[0];
		
		      if (res.tempFilePaths[0]) {
		        console.log('开始压缩图片'); // 打印日志，确认进入压缩图片的逻辑
		        uni.compressImage({
		          src: res.tempFilePaths[0], // 使用 tempFilePaths[0] 作为路径字符串
		          quality: 50, // 压缩质量，范围0-100，数值越大，质量越高
		          success: function(compressRes) {
		            console.log('压缩成功:', compressRes); // 打印压缩结果
		            imgUrl.value = compressRes.tempFilePath;
					xx.value.goodsPice=imgUrl.value
		            console.log('压缩后的图片路径:', imgUrl.value);
		          },
		          fail: function(compressErr) {
		            console.error('压缩失败:', compressErr);
		            uni.showToast({
		              title: '压缩失败',
		              icon: 'none',
		              duration: 2000
		            });
		          }
		        });
		      } else {
		        console.error('图片路径为空字符串');
		        uni.showToast({
		          title: '图片路径无效',
		          icon: 'none',
		          duration: 2000
		        });
		      }
		    } else {
		      console.error('没有选择图片');
		      uni.showToast({
		        title: '请选择图片',
		        icon: 'none',
		        duration: 2000
		      });
		    }
		  },
		  fail: function(err) {
		    console.error('选择图片失败:', err);
		    uni.showToast({
		      title: '选择图片失败',
		      icon: 'none',
		      duration: 2000
		    });
		  }
		});
	}
//提交
const submit =async () => {
  // 校验所有字段
  Object.keys(xx.value).forEach(field => validateTitle(field));
  console.log(Object.keys(validationErrors).length)
  // 如果没有错误，则提交表单
  if (Object.keys(validationErrors).length == 5) {
    console.log('提交的数据:', xx.value);
	let res=await http({
		url:'/lft/goods/add',
		method:'post',
		data:xx.value
	})
	console.log(xx.value.goodsPice)
	uni.uploadFile({
	  url: 'http://localhost:8080/lft/goods/tupian', // 服务器的上传接口地址
	  filePath: xx.value.goodsPice, // 图片的临时文件路径
	  name: 'file',
	  success: function(uploadRes) {
	    console.log('上传成功:', uploadRes); // 打印上传结果
	    const serverResponse = JSON.parse(uploadRes.data);
	    console.log('服务器返回:', serverResponse);
	    // 更新 imgUrl.value 为服务器返回的路径（如果需要）
	    // imgUrl.value = serverResponse.filePath;
	  },
	  fail: function(uploadErr) {
	    console.error('上传失败:', uploadErr);
	    uni.showToast({
	      title: '上传失败',
	      icon: 'none',
	      duration: 2000
	    });
	  }
	});
	if(res.code==200){
		uni.showToast({
		  title: res.data,
		  icon: 'success',
		  duration: 2000
		});
	}else{
		uni.showToast({
		  title: '添加失败',
		  icon: 'error',
		  duration: 2000
		});
	}
    // 清空表单
    xx.value.goodsName = '';
    xx.value.goodsUnit = '';
    xx.value.categoryId = '';
    xx.value.gjprices = '';
	xx.value.varietys='';
	xx.value.introduces='';
	imgUrl.value=''
  } else {
    uni.showToast({
      title: '请填写完整',
      icon: 'none',
      duration: 2000
    });
  }
};
onLoad(()=>{
		shangpinff()
	})
</script>

<style>
	.ss{
		width: 100%;
		height: 100vh;
		display: grid;
		place-items: center;
		
	}
	.content{
		width: 80%;
	}
	.sahngpintupian {
		width: 100%;
		height: 500rpx;
		border: 2rpx solid black;
		background-image: url('../../../static/img-scspt@2x.png');
		background-size: cover; /* 背景图片覆盖整个容器 */
		  background-position: center; /* 背景图片居中 */
		  background-repeat: no-repeat; /* 防止背景图片重复 */
	}
	
	
	
	button {
	  margin-bottom: 20px;
	}
	
	image {
	  width: 100%;
	  max-width: 300px;
	  border-radius: 8px;
	}
	.uni-mt-5{
		background-color: #F5F6F8;
	}
</style>
